package com.leicx.guli.common.validate;

import com.leicx.guli.common.enums.GuliExceptionEnum;
import com.leicx.guli.common.exception.RRException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author daxiong
 * @date 2021/6/4 9:35 下午
 */
public class RegularStringValidator implements ConstraintValidator<RegularString, String> {

    private int min;
    private int max;
    private String regex;

    public RegularStringValidator() {
        System.out.println("新建对象：" + min);
    }

    @Override
    public void initialize(RegularString constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        regex = "^[a-zA-Z]{" + min + "," + max + "}$";
        validateParameters();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return Pattern.matches(regex, value);
    }

    private void validateParameters() {
        if (min < 0) {
            throw new RRException(GuliExceptionEnum.PARAMETER_CHECK_ERROR);
        }
        if (max < 0) {
            throw new RRException(GuliExceptionEnum.PARAMETER_CHECK_ERROR);
        }
        if (max < min) {
            throw new RRException(GuliExceptionEnum.MAX_LESS_MIN);
        }
    }
}
